﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace CommonHelp
{
    public class DataHelper
    {
        /// <summary>
        /// 合并两个表，根据主表合并附表，附表中多余的记录将被抛弃
        /// </summary>
        /// <param name="mainTab">主表</param>
        /// <param name="appendTab">附表</param>
        /// <param name="keyFieldName">两个表关联字段</param>
        /// <param name="replaceMainTab"></param>
        public static void CombineTab(ref DataTable mainTab, DataTable appendTab, string keyFieldName)
        {
            ////合并列
            for (int i = 0; i < appendTab.Columns.Count; i++)
            {
                DataColumn appCol = appendTab.Columns[i];
                if (mainTab.Columns.Contains(appCol.ColumnName))
                {
                    continue;
                }
                DataColumn newCol = new DataColumn()
                {
                    ColumnName = appCol.ColumnName,
                    DefaultValue = appCol.DefaultValue,
                    DataType = appCol.DataType,
                    DateTimeMode = appCol.DateTimeMode,
                    ReadOnly = appCol.ReadOnly,
                };
                mainTab.Columns.Add(newCol);
            }
            ////合并行 
            for (int i = 0; i < appendTab.Rows.Count; i++)
            {
                DataRow appDr = appendTab.Rows[i];
                //for (int j = 0; j < appendTab.Columns.Count; j++)
                {
                    //DataColumn appCol = appendTab.Columns[j];
                    DataRow[] mainRows = mainTab.Select(keyFieldName + " = '" + appDr[keyFieldName] + "'");
                    if (mainRows == null || mainRows.Length == 0)
                    {
                        continue;
                    }
                    CombineRows(ref mainRows, appDr);
                }
            }
        }

        private static void CombineRows(ref DataRow[] mainRows, DataRow appDr)
        {
            for (int i = 0; i < mainRows.Length; i++)
            {
                DataRow mainRow = mainRows[i];
                for (int j = 0; j < appDr.Table.Columns.Count; j++)
                {
                    string colName = appDr.Table.Columns[j].ColumnName;
                    if (mainRow.Table.Columns[colName].ReadOnly)
                    {
                        continue;
                    }
                    mainRow[colName] = appDr[j];
                }
            }
        }
    }
}
